var express = require('express');
var router = express.Router();
var config = require('../config');
var http = require('client-http')
var path = require('path');
// var ejs = require();



router.get('/auth', function (req, res) {
    var code = req.query.code;
    http.request(config.auth.uc_private + config.auth.token_path, function (data) {
        var dataJson = JSON.parse(data);
        var access_token = dataJson.access_token;
        http.get(config.auth.uc_private + config.auth.user_path + '?access_token=' + access_token, function (user_data) {
            var userJson = JSON.parse(user_data);
            req.session.user = userJson.user;
            res.redirect('/');
        });
    }, "grant_type=authorization_code&client_id=" + config.auth.client_id + "&client_secret=" + config.auth.client_secret + "&code=" + code, {"Content-Type": "application/x-www-form-urlencoded"});
});



/* GET home page. */
router.get('/', function(req, res, next) {
        res.redirect('/home');
    }
);
router.get('/home', function(req, res, next) {
       if (req.session.user) {
            next();
        } else {
                var client_id = config.auth.client_id;
                var client_secret = config.auth.client_secret;
                var back_uri = config.auth.back_uri;
                var client_name = config.auth.client_name;
                var uc = config.auth.uc;
                var help = config.beeki;
                res.redirect(uc+'/oauth/authLogin?client_id=' + client_id + '&client_secret=' + client_secret + '&back_uri=' + back_uri);
        }
    },
    function(req, res, next){
        res.render('../index_prod', {user: req.session.user});
    }
);

module.exports = router;
